package com.tanglon.listener;

import com.tanglon.config.RabbitMQConfig;
import com.tanglon.domain.entity.ArticleViewMessage;
import com.tanglon.service.ArticleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class ArticleViewConsumer {

    @Autowired
    private ArticleService articleService;

    @Autowired
    public RedisTemplate redisTemplate;


    // 滑动窗口时长：15分钟（可根据业务调整）
    private static final long WINDOW_DURATION = 15;
    private static final TimeUnit WINDOW_TIME_UNIT = TimeUnit.MINUTES;

    @RabbitListener(queues = RabbitMQConfig.ARTICLE_VIEW_QUEUE)
    public void handleArticleView(ArticleViewMessage message){


        Long articleId = null;

        articleId = message.getArticleId();
        Long userId=message.getUserKey();
        // 1. 生成滑动窗口的Redis唯一键：格式为 "article:view:window:{文章ID}:{用户标识}"
        String windowKey = "article:view:window:" + articleId + ":" + userId;

        // 2. 判断该用户在窗口内是否已浏览过（键是否存在）
        Boolean hasViewed = redisTemplate.hasKey(windowKey);
        if (Boolean.FALSE.equals(hasViewed)) {
            // 3. 窗口内首次浏览：更新数据库浏览量，并记录Redis窗口标记
            articleService.updateViewCount(articleId);
            // 设置键过期时间（15分钟），过期后自动删除，视为窗口结束
            redisTemplate.opsForValue().set(windowKey, "1", WINDOW_DURATION, WINDOW_TIME_UNIT);
        } else {
            // 4. 窗口内重复浏览：不更新浏览量（可添加日志用于监控）
            log.info("用户{}在{}分钟内已浏览过文章{}，不重复计数", userId, WINDOW_DURATION, articleId);
        }

    }

}
